package com.example.helloworld.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileController {
    @PostMapping("/upload")
    public String up(
            //不一定要输入
            @RequestParam(required = false) String name,
            @RequestParam(required = false)  MultipartFile f,
            HttpServletRequest request) throws IOException {
        System.out.println(f.getContentType());
        System.out.println(f.getOriginalFilename());
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(f, path);
        return "上传成功";
    }

    public void saveFile(MultipartFile f, String path) throws IOException {
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(path+f.getOriginalFilename());
        f.transferTo(file);
    }

}
